import tinymce from 'tinymce/tinymce'
import { StdNakedFigure } from './naked_figure'
import { StdTableV2 } from './table'
import { StdBulletListV2 } from './bullet'
import { StdFigureV2 } from './figure'
import { StdFormulaV2 } from './formula'
import { StdParagraphV2 } from './paragraph'
import { isListTitle, spanTypes } from '@/constants/structure'
import { StdBlock } from './block'
import { StdExampleTextDataV2 } from './example'
import { StdItemNoteTextDataV2 } from './itemNote'
import store from '@/store'

/** 遍历节点树，获取节点内容，内容为数组
 *  tosave=true用于内容保存,不需要解析, false用于大纲解析和展示,需要解析
 */
export function parsePageData(pageNode, tosave = false) {
  const blockList = []
  // figure图的编号，全文连续，附录中每页的图编号独立
  let figureAnnexNumber = 0,
    prevAnnexNumber = 'A',
    figureIntroductionNumber = 0
  // 表格的编号，全文连续，附录中每页的图编号独立
  let tableAnnexNumber = 0,
    tableIntroductionNumber = 0
  // 列项数据块的最后索引
  let bulletEndIndex = -1
  const filterFn = (node) => {
    //.list-title, item_note
    if (tinymce.activeEditor.dom.is(node, 'div.term-block *')) {
      return !tosave
    }
    if (tinymce.activeEditor.dom.is(node, 'table')) {
      return true
    }
    if (tinymce.activeEditor.dom.getParent(node, 'table')) {
      return false
    }
    // 保留的项
    return true
  }
  const dataTypeNodes = [...pageNode.querySelectorAll('[data-type]')].filter(filterFn)
  dataTypeNodes.forEach((node, index) => {
    const dataType = node?.dataset?.type
    if (!dataType) return
    const blockId = node?.dataset?.blockId
    const groupId = node?.dataset?.groupId
    const referredId = node?.dataset?.referredId
    const blockType = node?.dataset?.blockType
    let blockIndex, tableData, bulletData, figureData, textData, formulaData, exampleData, abbrData, termData
    if (dataType === 'naked_figure') {
      // 图片
      figureData = new StdNakedFigure(node).data
    } else if (dataType === 'figure') {
      // 图片
      if (node.classList.contains('figure-annex')) {
        // 附录中的图
        const dataFigureAnnexNumber = node.dataset.figureAnnexNumber
        figureAnnexNumber = prevAnnexNumber === dataFigureAnnexNumber ? ++figureAnnexNumber : 1
        prevAnnexNumber = dataFigureAnnexNumber
        figureData = new StdFigureV2(node, figureAnnexNumber).data
      } else if (node.classList.contains('figure-introduction')) {
        figureData = new StdFigureV2(node, ++figureIntroductionNumber).data
      } else {
        const figureNumber = node.dataset.number
        figureData = new StdFigureV2(node, figureNumber).data
      }
    } else if (dataType === 'table') {
      if (node.classList.contains('table-annex')) {
        // 附录中的表
        const dataTableAnnexNumber = node.dataset.tableAnnexNumber
        tableAnnexNumber = prevAnnexNumber === dataTableAnnexNumber ? ++tableAnnexNumber : 1
        prevAnnexNumber = dataTableAnnexNumber
        tableData = new StdTableV2(node, tableAnnexNumber).data
      } else if (node.classList.contains('table-introduction')) {
        // 引言中的表
        tableData = new StdTableV2(node, ++tableIntroductionNumber).data
      } else {
        tableData = new StdTableV2(node).data
      }
    } else if (dataType === 'formula') {
      formulaData = new StdFormulaV2(node).data // 公式
    } else if (dataType === 'terms') {
      const termBlock = store.state.xmleditor.termBlockList.find((i) => i.blockId === blockId)
      if (termBlock) {
        termData = termBlock?.termData
        if (node.dataset?.contentNumber) {
          termData.contentNumber = node.dataset?.contentNumber
        }
      } else {
        console.warn('===错误的术语数据===')
      }
    } else if (dataType === 'abbreviation') {
      abbrData = store.state.xmleditor.abbrTableData.abbrData
    } else if (dataType === 'example') {
      exampleData = new StdExampleTextDataV2(node).data // 示例
    } else if (dataType === 'item_note') {
      textData = new StdItemNoteTextDataV2(node).data // 注
    } else if (dataType === 'item_list') {
      // 从第一个列项开始处理
      if (bulletEndIndex < index) {
        // 列项在html中是平级的，需要整合成一个对象
        const { list, endIndex } = getChainedBulletNodes(dataTypeNodes, index)
        bulletData = new StdBulletListV2(list).data
        bulletEndIndex = endIndex
      } else {
        // 列项已经被整合到第一项中处理
        return
      }
    } else if (dataType !== 'blank_page') {
      textData = new StdParagraphV2(node).data // 段落，包括 dataType === 'paragraph'
    }

    // 序号
    if (isListTitle(dataType)) {
      const selector = `#tinymce>.page-wrapper [data-block-id=${blockId}][data-type=${dataType}]`
      blockIndex = tinymce.activeEditor.dom.select(selector)?.[0]?.dataset?.index
    }

    // 上标 sup, 下标 sub, 组织部门 department，
    // 类型是行内块span标签，是paragraph的content内容
    const footnotes = ['figure_note', 'figure_footnote', 'table_note', 'footnote']
    if (![...footnotes, ...spanTypes].includes(dataType)) {
      const blockData = { tableData, bulletData, figureData, formulaData, textData, exampleData, abbrData, termData } // 块内容数据
      blockList.push(new StdBlock({ groupId, referredId, dataType, blockId, blockType, blockIndex, ...blockData }))
    }

  })

  return blockList
}

// 整合列项
function getChainedBulletNodes(nodes, startIndex) {
  let bulletList = [nodes[startIndex]]
  const dataLang = nodes[startIndex].dataset.lang
  let i = startIndex + 1
  for (let len = nodes.length; i < len; i++) {
    const item = nodes[i]
    if (item.dataset?.type === 'item_list' && item.dataset?.lang === dataLang) {
      bulletList.push(item)
    } else if (item.parentNode?.classList.contains('item_list') && item.parentNode?.dataset.lang === dataLang) {
      // 忽略列项中的子元素
      continue
    } else {
      i--
      break
    }
  }
  return {
    list: bulletList,
    endIndex: i
  }
}
